import { useState, useEffect, useRef } from 'react'
import { Card, Grid, Statistic, Space, Typography, Spin, Empty, Message } from '@arco-design/web-react'
import {
  IconDesktop,
  IconFile,
  IconCodeBlock,
  IconClockCircle,
} from '@arco-design/web-react/icon'
import { getNodeStatistics } from '@/api/node'
import { getRunningInstances } from '@/api/task'
import { getDashboardStatistics, getBuildTrend } from '@/api/statistics'
import { signalRService, HubEvent, type NodeStatusData } from '@/utils/websocket'
import type { PipelineInstance } from '@/types'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import './index.css'

const { Row, Col } = Grid
const { Title } = Typography

interface DashboardStats {
  onlineNodes: number
  totalNodes: number
  runningTasks: number
  todayBuilds: number
  avgBuildTime: number
  successRate: number
}

export default function Dashboard() {
  const [loading, setLoading] = useState(true)
  const [stats, setStats] = useState<DashboardStats>({
    onlineNodes: 0,
    totalNodes: 0,
    runningTasks: 0,
    todayBuilds: 0,
    avgBuildTime: 0,
    successRate: 0,
  })
  const [recentInstances, setRecentInstances] = useState<PipelineInstance[]>([])
  const taskStatusChartRef = useRef<HTMLDivElement>(null)
  const buildTrendChartRef = useRef<HTMLDivElement>(null)

  // 加载仪表盘数据
  const loadDashboardData = async () => {
    try {
      // 使用 Promise.allSettled 处理部分 API 失败的情况
      const results = await Promise.allSettled([
        getNodeStatistics(),
        getRunningInstances(),
        getDashboardStatistics(),
      ])

      // 处理节点统计
      const nodeStats = results[0].status === 'fulfilled'
        ? results[0].value
        : { onlineNodes: 0, totalNodes: 0, offlineNodes: 0 }

      // 处理运行中的任务
      const runningTasks = results[1].status === 'fulfilled'
        ? results[1].value
        : []

      // 处理仪表盘统计
      const dashboardStats = results[2].status === 'fulfilled'
        ? results[2].value
        : null

      // 计算统计数据
      const newStats: DashboardStats = {
        onlineNodes: nodeStats.onlineNodes,
        totalNodes: nodeStats.totalNodes,
        runningTasks: runningTasks.length,
        todayBuilds: dashboardStats?.todayBuilds || 0,
        avgBuildTime: dashboardStats?.avgBuildTimeMinutes || 0,
        successRate: dashboardStats?.successRate || 0,
      }

      setStats(newStats)
      setRecentInstances(runningTasks.slice(0, 5))
    } catch (error) {
      console.error('Failed to load dashboard data:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadDashboardData()

    // 节点状态更新回调
    const handleNodeStatus = (data: NodeStatusData) => {
      console.log('Node status update:', data)
      // 重新加载节点统计
      loadDashboardData()
    }

    // 连接 WebSocket 进行实时更新
    const connectWebSocket = async () => {
      try {
        await signalRService.connect()
        signalRService.on(HubEvent.RECEIVE_NODE_STATUS, handleNodeStatus)
        await signalRService.subscribeNodeStatus()
      } catch (error) {
        console.warn('WebSocket 连接失败,将使用轮询模式:', error)
        // WebSocket 连接失败不影响页面功能
      }
    }

    connectWebSocket()

    // 每30秒自动刷新一次作为备用
    const timer = setInterval(loadDashboardData, 30000)

    return () => {
      clearInterval(timer)
      signalRService.off(HubEvent.RECEIVE_NODE_STATUS, handleNodeStatus)
      signalRService.unsubscribeNodeStatus().catch(console.error)
    }
  }, [])

  // 任务状态分布图表
  useEffect(() => {
    if (!taskStatusChartRef.current || recentInstances.length === 0) return

    const chart = echarts.init(taskStatusChartRef.current)

    const statusCounts = recentInstances.reduce((acc, instance) => {
      const status = instance.status
      acc[status] = (acc[status] || 0) + 1
      return acc
    }, {} as Record<number, number>)

    const option = {
      title: {
        text: '任务状态分布',
        left: 'center',
        top: 10,
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'middle',
      },
      series: [
        {
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: [
            { value: statusCounts[0] || 0, name: '等待中', itemStyle: { color: '#86909c' } },
            { value: statusCounts[1] || 0, name: '运行中', itemStyle: { color: '#165dff' } },
            { value: statusCounts[2] || 0, name: '成功', itemStyle: { color: '#00b42a' } },
            { value: statusCounts[3] || 0, name: '失败', itemStyle: { color: '#f53f3f' } },
            { value: statusCounts[4] || 0, name: '已取消', itemStyle: { color: '#ff7d00' } },
          ].filter(item => item.value > 0),
        },
      ],
    }

    chart.setOption(option)

    return () => {
      chart.dispose()
    }
  }, [recentInstances])

  // 构建趋势图表
  useEffect(() => {
    if (!buildTrendChartRef.current) return

    const chart = echarts.init(buildTrendChartRef.current)

    // 尝试获取真实数据,如果失败则使用示例数据
    const loadBuildTrendData = async () => {
      try {
        const trendData = await getBuildTrend(7)

        const days = trendData.map((item) => dayjs(item.date).format('MM-DD'))
        const successData = trendData.map((item) => item.successCount)
        const failedData = trendData.map((item) => item.failedCount)

        const option = {
          title: {
            text: '构建趋势(最近7天)',
            left: 'center',
            top: 10,
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
            },
          },
          legend: {
            data: ['成功', '失败'],
            top: 40,
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: 80,
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: days,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '成功',
              type: 'bar',
              stack: 'total',
              itemStyle: {
                color: '#00b42a',
              },
              data: successData,
            },
            {
              name: '失败',
              type: 'bar',
              stack: 'total',
              itemStyle: {
                color: '#f53f3f',
              },
              data: failedData,
            },
          ],
        }

        chart.setOption(option)
      } catch (error) {
        console.error('Failed to load build trend data:', error)

        // 使用示例数据
        const days = []
        const successData = []
        const failedData = []

        for (let i = 6; i >= 0; i--) {
          days.push(dayjs().subtract(i, 'day').format('MM-DD'))
          successData.push(Math.floor(Math.random() * 20) + 10)
          failedData.push(Math.floor(Math.random() * 5))
        }

        const option = {
          title: {
            text: '构建趋势(最近7天 - 示例数据)',
            left: 'center',
            top: 10,
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
            },
          },
          legend: {
            data: ['成功', '失败'],
            top: 40,
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: 80,
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: days,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '成功',
              type: 'bar',
              stack: 'total',
              itemStyle: {
                color: '#00b42a',
              },
              data: successData,
            },
            {
              name: '失败',
              type: 'bar',
              stack: 'total',
              itemStyle: {
                color: '#f53f3f',
              },
              data: failedData,
            },
          ],
        }

        chart.setOption(option)
      }
    }

    loadBuildTrendData()

    return () => {
      chart.dispose()
    }
  }, [])

  if (loading) {
    return (
      <div className="dashboard">
        <Card>
          <div style={{ textAlign: 'center', padding: '100px 0' }}>
            <Spin size={40} />
          </div>
        </Card>
      </div>
    )
  }

  return (
    <div className="dashboard">
      <Title heading={4} style={{ marginBottom: 20 }}>
        仪表盘
      </Title>

      <Row gutter={16}>
        <Col span={6}>
          <Card hoverable>
            <Statistic
              title="在线节点"
              value={stats.onlineNodes}
              suffix={`/ ${stats.totalNodes}`}
              prefix={<IconDesktop style={{ color: '#0fc6c2' }} />}
              styleValue={{ color: '#0fc6c2' }}
            />
          </Card>
        </Col>

        <Col span={6}>
          <Card hoverable>
            <Statistic
              title="运行中的任务"
              value={stats.runningTasks}
              prefix={<IconFile style={{ color: '#f77234' }} />}
              styleValue={{ color: '#f77234' }}
            />
          </Card>
        </Col>

        <Col span={6}>
          <Card hoverable>
            <Statistic
              title="今日构建"
              value={stats.todayBuilds}
              prefix={<IconCodeBlock style={{ color: '#722ed1' }} />}
              styleValue={{ color: '#722ed1' }}
            />
          </Card>
        </Col>

        <Col span={6}>
          <Card hoverable>
            <Statistic
              title="平均构建时间"
              value={stats.avgBuildTime}
              suffix="分钟"
              precision={1}
              prefix={<IconClockCircle style={{ color: '#3491fa' }} />}
              styleValue={{ color: '#3491fa' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={16} style={{ marginTop: 20 }}>
        <Col span={12}>
          <Card>
            <div ref={taskStatusChartRef} style={{ height: 300 }}>
              {recentInstances.length === 0 && (
                <Empty description="暂无运行中的任务" style={{ paddingTop: 100 }} />
              )}
            </div>
          </Card>
        </Col>
        <Col span={12}>
          <Card>
            <div ref={buildTrendChartRef} style={{ height: 300 }} />
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginTop: 20 }}>
        <Col span={24}>
          <Card title="快速入门" bordered={false}>
            <Space direction="vertical" size="large">
              <div>
                <Title heading={6}>欢迎使用 SumerCore DevOps 平台！</Title>
                <Typography.Paragraph>
                  这是一个企业级 DevOps 自动化平台，支持工作流可视化编排、分布式任务调度监控等功能。
                </Typography.Paragraph>
              </div>

              <div>
                <Title heading={6}>快速开始：</Title>
                <ul>
                  <li>1. 在"工作流管理"中创建您的第一个工作流</li>
                  <li>2. 在"流水线管理"中关联工作流到代码仓库</li>
                  <li>3. 在"节点管理"中注册执行节点</li>
                  <li>4. 在"任务监控"中查看实时执行状态</li>
                </ul>
              </div>
            </Space>
          </Card>
        </Col>
      </Row>
    </div>
  )
}
